<?php

namespace App\Http\Controllers\UserApi;

use App\Http\Controllers\Controller;
use App\Models\ClassBaseInfo;
use App\Models\GroupClassInfo;
use App\Models\UserSubscribe;
use App\Services\Admin\Reservation;
use Illuminate\Http\Request;
use App\Models\GroupClass;
use App\Services\Api\GroupClassServices;
use App\Http\Requests\UserApi\GroupRequest;
use Illuminate\Support\Facades\DB;
use App\Services\Api\UserIntegralServices;
use App\Models\CampOrder;
use App\Services\Api\UserRankExpServices;


class GroupClassController extends BaseController
{
    public function group_list(GroupClass $groupClass,GroupClassServices $groupClassServices){
        $data = $groupClassServices->group_class_list($groupClass);
        return self::success($data);
    }

    public function group_info(GroupRequest $groupRequest,GroupClassServices $groupClassServices){
        $data = $groupClassServices->group_class_info($groupRequest->input('group_class_id'));
        return self::success($data);
    }

    public function by_group(GroupRequest $groupRequest,GroupClassServices $groupClassServices,UserSubscribe $subscribe,UserIntegralServices $integralServices,CampOrder $campOrder){
        //dd(111);
        //开启事务
        DB::beginTransaction();
        try{
            $groupClassModel = new GroupClass();
            $classObj = $groupClassModel
                ->with([
                    'group_class_info'=>function($q){
                        $q->with([
                            'class_base_info'=>function($q){
                                $q->with([
                                    'class_base'=>function($q){
                                        $q->select(['id','class_name','class_price']);
                                    },
                                    'teacher'=>function($q){
                                        $q->select(['id','teacher_name']);
                                    },
                                    'classsroom'=>function($q){
                                        $q->select(['id','numbering']);
                                    },
                                    'store'=>function($q){
                                        $q->select(['id','store_name']);
                                    },
                                ]);
                            },
                        ]);
                    },
                ])
                ->where('id',$groupRequest->input('group_class_id'))
                ->first()
                ->toArray();

            $my_camp_obj = $campOrder->where('group_class_id',$groupRequest->input('group_class_id'))
                ->where('user_id',auth('api') -> user()->id)
                ->first();

            if(!empty($my_camp_obj)){
                return self::fail('請不要重複購買');
            }

            $all_camp_obj = $campOrder->where('group_class_id',$groupRequest->input('group_class_id'))
                //->where('user_id',auth('api') -> user()->id)
                ->count();

            if($classObj['buy_number'] <= $all_camp_obj){
                return self::fail('購買人數上限');
            }

            $new_time = time();

            $registration_start_time = $classObj['registration_start_time'];
            $registration_time = $classObj['registration_time'];

            if(!empty($registration_start_time) && !empty($registration_time)) {
                //檢查過期
                if ($new_time < strtotime("{$registration_start_time}") || $new_time > strtotime("{$registration_time}")) {
                    return self::fail('沒到報名時間或者已過報名期');
                }
            }

            //dd($integralServices->available_integral(auth('api') -> user()->id)); plan_date
            if($integralServices->available_integral(auth('api') -> user()->id) < ($classObj['group_class_price'])){
                return self::fail('积分不足');
            }

            $data = [];

            //数据组装
            foreach ($classObj['group_class_info'] as $k=>$v){
                if($v['plan_date'] < date("Y-m-d H:i:s")){
                    return self::fail('camp套餐内有过期课程不能购买');
                }

                $data[$k]['user_id'] = auth('api') -> user()->id;
                $data[$k]['class_base_id'] = $v['class_base_info']['class_base_id'];

                $data[$k]['class_base_info_id'] = $v['class_base_info']['id'];

                $data[$k]['store_id'] = $v['class_base_info']['store_id'];
                $data[$k]['class_name'] = $v['class_base_info']['class_base']['class_name'];
                $data[$k]['store_name'] = $v['class_base_info']['store']['store_name'];
                $data[$k]['class_classroom_id'] = $v['class_base_info']['classsroom']['id'];
                $data[$k]['class_classroom_name'] = $v['class_base_info']['classsroom']['numbering'];

                //用于查询上课老师
                $class_bass_info_teacher_arr = Reservation::class_bass_info_teacher_result($v['class_base_info']['id'])->get()->toArray();

                $teacher = Reservation::class_bass_info_teacher_arr($class_bass_info_teacher_arr);

                if(empty($teacher['id']))throw new \Exception('該camp沒安排老師上課不允許購買，請聯係客服!');

                $data[$k]['teacher_id'] = $teacher['id'];
                $data[$k]['teacher_name'] = $teacher['teacher_name'];

                $data[$k]['class_info'] = json_encode($classObj);
                $data[$k]['subscribe_status'] = 2;

                $time = explode('~',$v['class_base_info']['class_time']);

                if(count($time)>0){
                    //去时分秒，代码兼容问题
                    $subscribe_time = date("Y-m-d",strtotime($v['plan_date']));
                    $subscribe_time = strtotime($subscribe_time);
                    //dd($subscribe_time,$time,HisToS($time[0]));
                    $start_time = $subscribe_time + HisToS($time[0]);
                    $end_time = $subscribe_time + HisToS($time[1]);
                }

                $data[$k]['buy_type'] = 2;
                $data[$k]['use_integral'] = $v['class_base_info']['class_base']['class_price'];

                $data[$k]['group_class_id'] = $classObj['id'];

                $data[$k]['class_time'] = date("Y-m-d H:i:s",$start_time);
                $data[$k]['end_time'] =  date("Y-m-d H:i:s",$end_time);
                $data[$k]['created_at'] = date("Y-m-d H:i:s");

            }

            $use_integral_msg = [
                '購買camp课程',
                "-{$classObj['group_class_price']}分",
                $classObj['group_class_name']
            ];

            //扣减积分
            $msg = implode("/",$use_integral_msg);;

            $is_use = $integralServices->use_integral(auth('api') -> user()->id,$classObj['group_class_price'],$msg);

            if(!$is_use){
                return self::fail('扣款失败');
            }

            $res = DB::table('user_subscribe')->insert($data);

            $campOrder->group_class_id = $groupRequest->input('group_class_id');
            $campOrder->user_id = auth('api') -> user()->id;
            $campOrder->group_price = $classObj['group_class_price'];
            $campOrder->save();

            DB::commit();
            if($res){
                return self::success();
            }
            return self::fail('保存失败');

        }catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            return self::fail($e->getMessage());
        }

    }

    public function change_camp_subscribe(GroupRequest $groupRequest)
    {
        try{
            $data = UserSubscribe::where('id', $groupRequest->subscribe_id)
                ->where('user_id',auth('api') -> user()->id)
                ->where('buy_type',2)
                ->first();

            if(empty($data)){
                throw new \Exception('沒有找到數據');
            }

            if($data->subscribe_status != 2 && $data->buy_type ==2){
                throw new \Exception('當前狀態不能請假');
            }

            //計算是否能請假
            $advance_cancel_time = GroupClass::where('id',$data->group_class_id)->value('advance_cancel_time');
           // dd($data->group_class_id);
            $remedial_teaching_number = GroupClass::where('id',$data->group_class_id)->value('remedial_teaching_number');

            $cancel_time = strtotime($data->class_time) - $advance_cancel_time * 60;
            if(time() > $cancel_time){
                throw new \Exception('超時不能請假');
            }

            //统计请假了几次
            $leave_number = UserSubscribe::where('group_class_id',$data->group_class_id)->where('user_id',auth('api') -> user()->id)
                ->where('subscribe_status',6)
                ->count();

            if($leave_number >= $remedial_teaching_number){
                throw new \Exception('你已超过該camp的請假上限,不能請假');
            }

            //计算请假失效时间
            $data->remedial_teaching_time = strtotime('+15 day');
            $data->subscribe_status = 6;
            $data->remarks = '請假';
            $res = $data->save();
            if($res){
                return self::success();
            }

        }catch (\Exception $e){
            return self::fail($e->getMessage());
        }

    }

    public function remedial_teaching(UserSubscribe $subscribe,Request $request){

    }

}
